package com.skycode.servlet;

import com.skycode.bean.NewsBean;
import com.skycode.dao.NewsDao;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 1.接受post网址 /newsAdd.jsp
 * 2.接受到传递过来的新闻参数 新闻标题 新闻内容
 * 3.完成新闻添加
 * 4.跳转到其他页面
 */
@WebServlet("/newsAdd.jsp")
public class NewsAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 会话获取管理昵称
        String user =(String) req.getSession().getAttribute("User");//获取会话
        if (user == null || user.equals("")){
            resp.sendRedirect("login.jsp");//没登陆 跳转登陆页面
            return;
        }
        String newsTitle = req.getParameter("NewsTitle");
        String newsContent = req.getParameter("NewsContent");
        NewsBean newsBean = new NewsBean();//实例化新闻对象
        newsBean.setNewsTitle(newsTitle);//设置新闻标题
        newsBean.setNewsContent(newsContent);//设置新闻内容
        NewsDao newsDao = new NewsDao();//实例化 新闻Dao
        newsDao.add(newsBean);//调用添加方法 传递新闻对象
        int result= newsDao.add(newsBean);
        //在Servlet有网页重定向功能 可以将网页跳转到指定位置
        if (result>0){
            resp.sendRedirect("news.jsp");
        }else{
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req, resp);
        }
        resp.sendRedirect("news.jsp");//参数是相对网址
    }
}
